const Sequelize = require('sequelize');

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  'postgres://postgres:password@localhost:6432/postgres';

async function confirmOrgInvite(sequelize, msg) {
  var res = await sequelize.query(
    'UPDATE org_member SET state= :state WHERE id = :orgMemberId',
    {
      replacements: {
        orgMemberId: msg.content.org_member_id,
        state: 'normal'
      }
    }
  );

  if (msg.content.teams !== null) {
    res = await sequelize.query(
      'SELECT * FROM team_member WHERE id in (:teams)',
      {
        replacements: {
          teams: msg.content.teams
        }
      }
    );
    for (var i = 0; i < res[0].length; i += 1) {
      res = await sequelize.query(
        'INSERT INTO team_member ( owner_id, user_id, path, create_by, role, state, is_team, name) values (:ownerId, :userId, :path, :createBy, :role, :state, :isTeam, :name);',
        {
          replacements: {
            isTeam: false,
            role: 'member',
            state: 'normal',
            name: '',
            ownerId: res[0][i].owner_id,
            userId: msg.user_to,
            createBy: msg.user_from,
            path: !res[0][i].path
              ? res[0][i].name
              : `${res[0][i].path}/${res[0][i].name}`
          }
        }
      );
    }
  }
  /* if (resultOrgMember && resultOrgMember[0] && resultOrgMember[0][0]) {
    console.log(resultOrgMember[0][0]);
    var orgMember = resultOrgMember[0][0];
    //add to sub teams

    //update org Member
    var res = await sequelize.query(
      "UPDATE org_member SET payment_valid=true WHERE id = :orgMemberId; ",
      {
        replacements: {
          orgMemberId: msg.content.org_member_id
        }
      }
    );
  } */
  return res;
}

async function confirmMsg(msg) {
  console.log('confirmMsg start', msg);
  if (msg.role === 'owner') return;
  try {
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
    var res;
    if (msg.type === 'invite_org_member') {
      res = await confirmOrgInvite(sequelize, msg);
    }
    return res;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.confirmMsg = confirmMsg;
